﻿using DBManager.Helper;
using DBManager.Model;
using DBManager.UserCode;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DBManager
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            this.Icon = MyResource.icon;

            btnBackupShow.Enabled = false;
            btnClearData.Enabled = false;
            btnClearData1.Enabled = false;
            btnClearData2.Enabled = false;
            btnDbList.Enabled = false;
            btnShowRestoreForm.Enabled = false;
        }
                
        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public string GetConnStr(string dbName = "master")
        {
            return SqlCommon.GetConnStr(txtServerName.Text.Trim(), txtUserName.Text.Trim(), txtPwd.Text.Trim(), dbName);
        }

        #region 数据库树加载

        /// <summary>
        /// 数据库连接后加载树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnDB_Click(object sender, EventArgs e)
        {
            btnConnDB.Enabled = false;
            btnConnDB.Text = "数据库连接中...";
            Task task = new Task(() =>
            {
                if (SqlCommon.ConnectTest(GetConnStr()))
                {
                    MessageBox.Show("数据库连接成功！", "提示");

                    btnBackupShow.Enabled = true;
                    btnClearData.Enabled = true;
                    btnClearData1.Enabled = true;
                    btnClearData2.Enabled = true;
                    btnDbList.Enabled = true;
                    btnShowRestoreForm.Enabled = true;

                    //txtServerName.Enabled = false;
                    //txtUserName.Enabled = false;
                    //txtPwd.Enabled = false;
                }
                btnConnDB.Enabled = true;
                btnConnDB.Text = "数据库连接";
            });
            task.Start();
        }

        private void btnDbList_Click(object sender, EventArgs e)
        {
            InitTree();
        }

        /// <summary>
        /// 数据库树加载
        /// </summary>
        private void InitTree()
        {
            DataTable dt = SqlCommon.GetDataBase(GetConnStr());
            tvDBList.Nodes.Clear();
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    node.Tag = dr["name"].ToString();
                    node.Text = dr["name"].ToString();
                    tvDBList.Nodes.Add(node);
                    InitTreeChild(node);
                }
                //tvDBList.ExpandAll();
            }
        }

        private void InitTreeChild(TreeNode node)
        {
            DataTable dt = SqlCommon.GetDataTable(GetConnStr(node.Tag.ToString()));
            List<string> hisDtList = XmlCommon.SelectDtList(FileCommon.xmlFilePath, node.Tag.ToString());
            foreach (DataRow dr in dt.Rows)
            {
                TreeNode childNode = new TreeNode();
                childNode.Tag = dr["name"].ToString();
                childNode.Text = dr["name"].ToString();
                if (hisDtList.Contains(dr["name"].ToString()))
                {
                    childNode.Checked = true;
                }
                node.Nodes.Add(childNode);
            }
            ChangeCheckState(node);
        }

        private void ChangeCheckState(TreeNode node)
        {
            bool hasChildChecked = false;
            foreach (TreeNode tn in node.Nodes)
            {
                if (tn.Checked)
                {
                    hasChildChecked = true;
                    break;
                }
            }
            node.Checked = hasChildChecked;
        }

        #region 鼠标点击事件&treeView Checkbox选择事件
        private void tvDBList_MouseClick(object sender, MouseEventArgs e)
        {
            TreeNode node = tvDBList.GetNodeAt(new Point(e.X, e.Y));
            if (node != null)
            {
                ChangeChild(node, node.Checked);//影响子节点
                ChangeParent(node);//影响父节点
            }
        }

        //递归子节点跟随其全选或全不选
        private void ChangeChild(TreeNode node, bool state)
        {
            node.Checked = state;
            foreach (TreeNode tn in node.Nodes)
            {
                ChangeChild(tn, state);
            }
        }

        //递归父节点跟随其全选或全不选
        private void ChangeParent(TreeNode node)
        {
            if (node.Parent != null)
            {
                //兄弟节点被选中的个数 
                int brotherNodeCheckedCount = 0;

                //遍历该节点的兄弟节点 
                foreach (TreeNode tn in node.Parent.Nodes)
                {
                    if (tn.Checked == true)
                    {
                        brotherNodeCheckedCount++;
                    }
                }

                //兄弟节点全没选，其父节点也不选 
                if (brotherNodeCheckedCount == 0)
                {
                    node.Parent.Checked = false;
                    ChangeParent(node.Parent);
                }

                //兄弟节点只要有一个被选，其父节点也被选 
                if (brotherNodeCheckedCount >= 1)
                {
                    node.Parent.Checked = true;
                    ChangeParent(node.Parent);
                }
            }
        }
        #endregion

        #endregion

        #region 清理数据表

        /// <summary>
        /// 清理数据表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearData_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("一经删除无法恢复，如需恢复请先提前备份，是否确认删除？", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                StringBuilder xmlSb = new StringBuilder();
                xmlSb.Append("<dblist>");
                bool isSelectDt = false;
                List<string> dtNames = new List<string>();

                string btnText = btnClearData.Text;
                btnClearData.Enabled = false;
                btnClearData.Text = "数据删除中...";
                tvDBList.Enabled = false;
                Task task = new Task(() =>
                {
                    foreach (TreeNode item in tvDBList.Nodes)
                    {
                        xmlSb.Append("<db dbname=\"" + item.Tag + "\">");

                        dtNames.Clear();
                        foreach (TreeNode childItem in item.Nodes)
                        {
                            if (childItem.Checked)
                            {
                                xmlSb.Append("<dt>");
                                xmlSb.Append(childItem.Tag);
                                xmlSb.Append("</dt>");

                                isSelectDt = true;
                                dtNames.Add(childItem.Tag.ToString());
                            }
                        }
                        xmlSb.Append("</db>");

                        if (dtNames.Count > 0)
                            ClearDataTableData(item.Tag.ToString(), dtNames);
                    }
                    xmlSb.Append("</dblist>");
                    if (isSelectDt)
                    {
                        XmlCommon.CreateXmlTree(FileCommon.xmlFilePath, xmlSb.ToString());
                    }
                    else
                        MessageBox.Show("请先选择要删除的表！");
                    btnClearData.Enabled = true;
                    btnClearData.Text = btnText;
                    tvDBList.Enabled = true;
                });
                task.Start();
            }
        }
        /// <summary>
        /// 删除表内数据
        /// </summary>
        /// <param name="connStr"></param>
        /// <param name="dtNames"></param>
        private void ClearDataTableData(string dbName, List<string> dtNames)
        {
            string connStr = GetConnStr(dbName);
            
                StringBuilder sbStr = new StringBuilder();
                foreach (string item in dtNames)
                {
                    sbStr.Append("delete from ");
                    sbStr.Append(item);
                    sbStr.Append("; ");
                }
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(sbStr.ToString(), conn);
                    cmd.CommandTimeout = 300;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show(dbName + "数据库下所选表删除成功！");
                }
        }

        #endregion

        #region 删除数据1，2

        private void btnClearData1_Click(object sender, EventArgs e)
        {
            string btnText = btnClearData1.Text;
            btnClearData1.Enabled = false;
            btnClearData1.Text = "数据删除中...";
            Task task = new Task(() =>
            {
                ClearData12(true);
                btnClearData1.Enabled = true;
                btnClearData1.Text = btnText;
            });
            task.Start();
        }

        private void btnClearData2_Click(object sender, EventArgs e)
        {
            string btnText = btnClearData2.Text;
            btnClearData2.Enabled = false;
            btnClearData2.Text = "数据删除中...";
            Task task = new Task(() =>
            {
                ClearData12(false);
                btnClearData2.Enabled = true;
                btnClearData2.Text = btnText;
            });
            task.Start();
        }

        private void ClearData12(bool isAll)
        {
            DialogResult dr = MessageBox.Show("删除数据前建议先执行备份操作，是否确定删除数据？", "提示", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                string clearSqlStr = ClearConfig.GetClearStr(isAll);

                string connStr = GetConnStr();
                if (SqlCommon.ConnectTest(connStr))
                {
                    SqlCommand cmd = new SqlCommand();
                    SqlConnection conn = new SqlConnection(connStr);
                    try
                    {
                        conn.Open();
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;
                        cmd.CommandText = clearSqlStr;
                        cmd.CommandTimeout = 300;
                        cmd.ExecuteNonQuery();
                        MessageBox.Show("删除成功！", "系统消息");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("删除失败，" + ex.Message, "系统消息");
                    }
                    finally
                    {
                        cmd.Dispose();
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
        }

        #endregion

        private void btnShowRestoreForm_Click(object sender, EventArgs e)
        {
            Restore restoreForm = new Restore(txtServerName.Text, txtUserName.Text, txtPwd.Text);
            restoreForm.ShowDialog();
        }

        private void btnBackupShow_Click(object sender, EventArgs e)
        {
            Backup backupForm = new Backup(txtServerName.Text, txtUserName.Text, txtPwd.Text);
            backupForm.ShowDialog();
        }

    }
}
